package com.hui.java.Synchronized;

/**
 * TODO: Synchronized同步代码块
 *
 * @author chenth
 * @create 2019-09-07 16:59
 **/
public class FirstSynchronized implements Runnable {

    /**
     * 当两个线程同时执行同一个对象的synchronized代码块时，一个时间内只能有一个线程得到执行，
     * 另一个线程必须等待当前线程执行完毕之后才能获得资源
     */
    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
            }
            System.out.println(Thread.currentThread().getName() + " is finished!");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        FirstSynchronized t1 = new FirstSynchronized();
        Thread thread1 = new Thread(t1, "A");
        Thread thread2 = new Thread(t1, "B");
        thread1.start();
        thread2.start();
    }
}
